package com.bookshop.util;

import cn.hutool.captcha.generator.RandomGenerator;
import com.bookshop.aspect.exception.CustomException;
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.github.qcloudsms.httpclient.HTTPException;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
public class SMSUtil {
    // 腾讯云短信应用的AppID
    private static final int APP_ID = 1400639492;
    // 腾讯云短信应用的AppKey
    private static final String APP_KEY = "5481e2e90fe857b727fa028ff8e657b8";
    // 短信模板ID
    private static final int TEMPLATE_ID = 1371294;
    // 短信签名
    private static final String SMS_SIGN = "小锋学代码个人网";

    public static void sendSms(String phoneNumber, String captcha) {
        try {
            // 实例化一个短信发送器
            SmsSingleSender sender = new SmsSingleSender(APP_ID, APP_KEY);
            // 短信参数，根据短信模板填写
            String[] params = {captcha};
            // 发送短信
            SmsSingleSenderResult result = sender.sendWithParam("86", phoneNumber, TEMPLATE_ID, params, SMS_SIGN, "", "");
            // 解析发送结果
            if (result.result == 0) {
                log.info("短信发送成功");
            } else {
                throw new CustomException("短信发送失败：" + result.errMsg);
            }
        } catch (HTTPException | IOException e) {
            e.printStackTrace();
        }
    }

    public static String getCaptcha(){
        return new RandomGenerator("0123456789", 6).generate();
    }
}